<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['name', 'is_directory', 'level', 'path'];
    protected $casts = [
        'is_directory' => 'boolean',
    ];

    protected static function boot()
    {
        parent::boot();
        // 监听 Category 的创建事件， 用户初始化 path 和 level 字段值
        static::creating(
            function (Category $category) {
                // 如果创建的是一个根目录
                if (is_null($category->parent_id)) {
                    // 将曾经设为 0
                    $category->level = 0;
                    // 将 path 设置为 -
                    $category->path = '-';
                } else {
                    // 将层级设为父类目的层级 + 1;
                    $category->level = $category->parent->level + 1;
                    // 将 path 值设置为父类目的 path 追加父类目 id 已经后面跟上一个 - 分隔符
                    $category->path = $category->parent->path.$category->parent_id.'-';
                }
            }
        );
    }

    public function parent()
    {
        return $this->belongsTo(Category::class);
    }

    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

    public function products()
    {
        return $this->hasMany(Product::class);
    }

    /**
     * 定一个访问器，获取祖先的类目 id 值
     *
     * @return array
     */
    public function getPathIdsAttribute()
    {
        // trim($str, '-' ) 字符串两端的 - 符号去掉
        // explode() 将字符串以 - 为分隔符切割为数组
        // 最后 array_filter 将数组中空的值移除
        return array_filter(explode('-', trim($this->path, '-')));
    }

    /**
     * 定一个访问器， 获取所有祖先 类目 并且按 层级排序
     *
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getAncestorsAttribute()
    {
        return Category::query()->whereIn('id', $this->path_ids)->orderBy('level')->get();
    }

    /**
     * 定一个访问器， 获取以 - 为分隔符的所有祖先类目名称及当前类目名称
     *
     * @return mixed
     */
    public function getFullNameAttribute()
    {
        return $this->ancestors->pluck('name')->push($this->name)->implode(' - ');
    }

}
